package org.liquidByte.trafficMustang.androidApp.dialogs;

import org.liquidByte.trafficMustang.R;
import org.liquidByte.trafficMustang.androidApp.App;
import org.liquidByte.trafficMustang.androidApp.services.LoginService;
import org.liquidByte.trafficMustang.androidApp.services.Services;
import org.liquidByte.trafficMustang.androidApp.services.dto.LoginDTO;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;

public class LoginDialog extends Dialog implements android.view.View.OnClickListener{

	private ImageButton imgbConfirmar;
	private EditText edtCpf;
	private EditText edtSenha;
	
	public LoginDialog(Context context, int theme) {
		super(context, theme);
		this.setContentView(R.layout.dialog_login);
		this.setTitle(R.string.msgs_login);
	}

	public LoginDialog(Context context) {
		super(context);
		this.setContentView(R.layout.dialog_login);
	}

	protected ImageButton getImgbConfirmar() {
		if (this.imgbConfirmar == null) {
			this.imgbConfirmar = (ImageButton)this.findViewById(R.id.dialog_login_confirmar);
		}
		return imgbConfirmar;
	}

	protected EditText getEdtCpf() {
		if (this.edtCpf == null) {
			this.edtCpf = (EditText)this.findViewById(R.id.dialog_login_cpf);
		}
		return edtCpf;
	}

	protected EditText getEdtSenha() {
		if (this.edtSenha == null) {
			this.edtSenha = (EditText)this.findViewById(R.id.dialog_login_senha);
		}
		return edtSenha;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (Services.isLoggedOn()) {
			this.cancel();
		} else {
			this.getImgbConfirmar().setOnClickListener(this);	
		}
	}

	@Override
	public void onClick(View v) {
		if (this.getImgbConfirmar() == v) {
			this.login();
		}
	}
	
	private void login() {
		LoginService service = Services.login();
		LoginDTO data = new LoginDTO();
		data.setDocumentoIdent(this.getEdtCpf().getText().toString());
		data.setSenha(this.getEdtSenha().getText().toString());
		
		try {
			service.auth(data);
			Services.setLoggedOn(true);
			this.dismiss();
		} catch (Exception e) {
			App.error(e);
		}
	}
	
}
